from sqlmodel import Field, SQLModel


class PermissionUser(SQLModel, table=True):
    __tablename__ = "permission_user"
    id: int = Field(primary_key=True)
    user_id: int = Field(foreign_key="user.id")
    permission_id: int = Field(foreign_key="generic_permissions.id")


class PermissionRole(SQLModel, table=True):
    __tablename__ = "permission_role"
    id: int = Field(primary_key=True)
    role_id: int = Field(foreign_key="role.id")
    permission_id: int = Field(foreign_key="generic_permissions.id")


class GenericPermissions(SQLModel, table=True):
    __tablename__ = "generic_permissions"
    id: int = Field(primary_key=True)
    code: str = Field(default=None, unique=True, index=True, nullable=False)
    description: str | None = Field(default=None)
    content_type_id: int = Field(default=None, nullable=False)
    object_id: int = Field(default=None, nullable=False)

    def __hash__(self):
        return hash(self.id)

    @property
    def assigned_users(self):
        _assigned_users = getattr(self, "directed_users", [])[:]
        for role in self.assigned_roles:
            _assigned_users.extend(role.users)

        return list(set(_assigned_users))
